package com.lucy.nepu.module.taward.lib;

import cn.hutool.core.lang.Validator;
import com.lucy.common.constant.HttpStatus;
import com.lucy.common.domain.PageResultDTO;
import com.lucy.common.exception.BusinessException;
import com.lucy.nepu.module.book.lib.BookDict;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Primary
@Slf4j
@Service
public class TAwardDictServiceImpl implements TAwardDictService {
    @Autowired
    TAwardDictDAO dao;

    @Override
    public TAwardDict getOneUnwrap(String s) {
        Optional<TAwardDict> dictOp = getOne(s);
        if (!dictOp.isPresent()){
            throw new BusinessException(HttpStatus.NOT_FOUND);
        }
        return dictOp.get();
    }

    @Override
    public PageResultDTO<TAwardDict> getAll(Pageable pageable, Example<TAwardDict> example) {
        Page<TAwardDict> page;

        if(Validator.isEmpty(example)){
            page = dao.findAll(pageable);
        }
        else {
            page = dao.findAll(example,pageable);
        }
        /*
          获取分页主体内容
         */
        List<TAwardDict> list = page.getContent();
        PageResultDTO<TAwardDict> pageResultDTO = new PageResultDTO<>();


        //封装分页请求结果
        pageResultDTO.setContent(list);
        pageResultDTO.setSize(page.getSize());
        pageResultDTO.setTotalPages(page.getTotalPages());
        pageResultDTO.setNumber(page.getNumber());
        pageResultDTO.setTotalElements(page.getTotalElements());
        return pageResultDTO;
    }

    @Override
    public List<TAwardDict> getExample(Example<TAwardDict> example) {
        return dao.findAll(example);
    }

    @Override
    public void deleteOne(String id) {
        dao.deleteById(id);
    }

    @Override
    public Optional<TAwardDict> getOne(String id) {
        return dao.findById(id);
    }

    @Override
    public TAwardDict saveOne(TAwardDict o) {
        if (Validator.isNotEmpty(o.getId())){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"新建DTO不可携带ID");
        }
        return dao.save(o);
    }

    @Override
    public TAwardDict updateOne(TAwardDict o) {
        if (Validator.isEmpty(o.getId())){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"更新DTO必须携带ID");
        }
        return dao.save(o);
    }
}
